package vip.geeker.iotms.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import vip.geeker.iotms.help.BusinessException;
import vip.geeker.iotms.help.Constants;
import vip.geeker.iotms.help.Response;
import vip.geeker.iotms.persistance.model.User;
import vip.geeker.iotms.service.impl.UserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
@Slf4j
@RequestMapping("/user")
public class UserController extends BaseController {
    @Resource
    private UserService userService;

    @GetMapping("toPage")
    public String toUserPage() {
        return Constants.USER_PAGE;
    }


    @GetMapping("toAddUser")
    public String toAddUser(HttpServletRequest request) {
        request.setAttribute("user",new User());
        return Constants.ADD_USER;
    }

    @GetMapping("/page")
    @ResponseBody
    public Object getUserPage(User user) {
        return new Response<>(userService.getUserPage(user));
    }

    @RequestMapping("/add")
    @ResponseBody
    public Object addUser(@RequestBody User user) {
        try {
            boolean addSuc = userService.addUser(user);
            if (addSuc) {
                return Constants.SUC_JSON;
            }
        } catch (BusinessException e) {
            return Response.error(e.getMessage());
        }
        return Response.error("操作失败");
    }

    @RequestMapping("/update")
    @ResponseBody
    public Object updateUser(@RequestBody User user) {
        try {
            boolean updateSuc = userService.updateUser(user);
            if (updateSuc) {
                return Constants.SUC_JSON;
            }
        } catch (BusinessException e) {
            return Response.error(e.getMessage());
        }
        return Response.error("操作失败");
    }

    @GetMapping("/queryUser")
    public String queryUser(HttpServletRequest request,Integer id) {
        User user = userService.selectByPrimaryKey(id);
        request.setAttribute("user",user);
        return Constants.ADD_USER;
    }


}
